<title>pyftpdlib Tutorial</title>
<a href="http://code.google.com/p/pyftpdlib"><img id="logo" src="logo.png" /></a>

<h1>Tutorial</h1>
<h1><a name="Table_of_contents" id="Table_of_contents">Table of contents</a></h1>
<ul>
  <li><a href="#Table_of_contents">Table of contents</a></li>
  <li><a href="#1.0_-_Introduction">1.0 - Introduction</a></li>
  <li><a href="#2.0_-_API_reference">2.0 - API reference</a></li>
  <li><a href="#3.0_-_Customizing_your_FTP_server">3.0 - Customizing your FTP server</a></li>
  <ul>
    <li><a href="#3.1_-_Building_a_Base_FTP_server">3.1 - Building a Base FTP server</a></li>
    <li><a href="#3.2_-_Logging_management">3.2 - Logging management</a></li>
    <li><a href="#3.3_-_Storing_passwords_as_hash_digests">3.3 - Storing passwords as hash digests</a></li>
    <li><a href="#3.4_-_Unix_FTP_Server">3.4 - Unix FTP Server</a></li>
    <li><a href="#3.5_-_Windows_NT_FTP_Server">3.5 - Windows NT FTP Server</a></li>
  </ul>
  <li><a href="#4.0_-_Advanced_usages">4.0 - Advanced usages</a></li>
  <ul>
    <li><a href="#4.1_-_FTPS_%28FTP_over_TLS/SSL%29_server">4.1 - FTPS (FTP over TLS/SSL) server</a></li>
    <li><a href="#4.2_-_Adding_bandwidth_throttling_capabilities">4.2 - Adding bandwidth throttling capabilities</a></li>
  </ul>
</ul>
<h1><a name="1.0_-_Introduction" id="1.0_-_Introduction">1.0 - Introduction</a></h1>
<p><a name="1.0_-_Introduction" id="1.0_-_Introduction">pyftpdlib implements the server side of the FTP protocol as defined in </a><a href="http://www.faqs.org/rfcs/rfc959.html" rel="nofollow">RFC-959</a>.  pyftpdlib consist of a single file, <a href="http://code.google.com/p/pyftpdlib/source/browse/trunk/pyftpdlib/ftpserver.py" rel="nofollow">ftpserver.py</a>, which contains a hierarchy of classes, functions and variables which implement the backend functionality for the ftpd. <br />
  This document is intended to serve as a simple <a href="http://code.google.com/p/billiejoex/wiki/Tutorial#2.0_-_API_reference" rel="nofollow">API reference</a> of most important classes and functions.  Also included is an introduction to <a href="http://code.google.com/p/billiejoex/wiki/Tutorial#3.0_-_Customizing_your_FTP_server" rel="nofollow">customization</a> through the use of some example scripts. Some of them are included in <a href="http://code.google.com/p/pyftpdlib/source/browse/#svn/trunk/demo" rel="nofollow">demo</a> directory of pyftpdlib source distribution. </p>
<p>If  you have written a customized configuration you think could be useful  to the community feel free to share it by adding a comment at the end  of this document. </p>
<h1><a name="2.0_-_API_reference" id="2.0_-_API_reference">2.0 - API reference</a></h1>
<p><a name="2.0_-_API_reference" id="2.0_-_API_reference">function ftpserver.<strong>log(</strong><em>msg</em><strong>)</strong> </a></p>
<blockquote><a name="2.0_-_API_reference" id="2.0_-_API_reference">Log messages intended for the end user. </a></blockquote>
<hr />
<a name="2.0_-_API_reference" id="2.0_-_API_reference">function ftpserver.<strong>logline(</strong><em>msg</em><strong>)</strong> </a>
<blockquote><a name="2.0_-_API_reference" id="2.0_-_API_reference">Log commands and responses passing through the command channel. </a></blockquote>
<hr />
<a name="2.0_-_API_reference" id="2.0_-_API_reference">function ftpserver.<strong>logerror(</strong><em>msg</em><strong>)</strong> </a>
<blockquote><a name="2.0_-_API_reference" id="2.0_-_API_reference">Log traceback outputs occurring in case of errors. </a></blockquote>
<hr />
<a name="2.0_-_API_reference" id="2.0_-_API_reference">class ftpserver.<strong>AuthorizerError</strong></a><strong><a href="http://code.google.com/p/pyftpdlib/w/edit/AuthorizerError"></a>()</strong>
<blockquote>Base class for authorizers exceptions. </blockquote>
<hr />
class ftpserver.<strong>DummyAuthorizer<a href="http://code.google.com/p/pyftpdlib/w/edit/DummyAuthorizer"></a>()</strong>
<blockquote>Basic  &quot;dummy&quot; authorizer class, suitable for subclassing to create your own  custom authorizers. An &quot;authorizer&quot; is a class handling authentications  and permissions of the FTP server. It is used inside FTPHandler  class for verifying user's password, getting users home directory,  checking user permissions when a filesystem read/write event occurs and  changing user before accessing the filesystem. DummyAuthorizer  is the base authorizer, providing a platform independent interface for  managing &quot;virtual&quot; FTP users. Typically the first thing you have to do  is create an instance of this class and start adding ftp users: </blockquote>
<pre>&gt;&gt;&gt; from pyftpdlib import ftpserver<br />&gt;&gt;&gt; authorizer = ftpserver.DummyAuthorizer()<br />&gt;&gt;&gt; authorizer.add_user('user', 'password', '/home/user', perm='elradfmw')<br />&gt;&gt;&gt; authorizer.add_anonymous('/home/nobody')</pre>
<ul>
  <li><strong>add_user(</strong><em>username</em>, <em>password</em>, <em>homedir</em><strong>[</strong>, <em>perm=&quot;elr&quot;</em><strong>[</strong>, <em>msg_login=&quot;Login successful.&quot;</em><strong>[</strong>, <em>msg_quit=&quot;Goodbye.&quot;</em><strong>]</strong><strong>]</strong><strong>])</strong> <br />
    Add a user to the virtual users table.  AuthorizerError exceptions raised on error conditions such as insufficient permissions or duplicate usernames.  Optional perm  argument is a set of letters referencing the user's permissions. Every  letter is used to indicate that the access rights the current FTP user  has over the following specific actions are granted. The available  permissions are the following listed below: </li>
</ul>
<blockquote>Read permissions:
  <ul>
    <li><strong>&quot;e&quot;</strong> = change directory (CWD command) </li>
    <li><strong>&quot;l&quot;</strong> = list files (LIST, NLST, MLSD commands) </li>
    <li><strong>&quot;r&quot;</strong> = retrieve file from the server (RETR command) </li>
  </ul>
  Write permissions
  <ul>
    <li><strong>&quot;a&quot;</strong> = append data to an existing file (APPE command) </li>
    <li><strong>&quot;d&quot;</strong> = delete file or directory (DELE, RMD commands) </li>
    <li><strong>&quot;f&quot;</strong> = rename file or directory (RNFR, RNTO commands) </li>
    <li><strong>&quot;m&quot;</strong> = create directory (MKD command) </li>
    <li><strong>&quot;w&quot;</strong> = store a file to the server (STOR, STOU commands</li>
  </ul>
Optional msg_login and msg_quit arguments can be specified to provide customized response strings when user log-in and quit.  The perm argument of the add_user()  method refers to user's permissions. Every letter is used to indicate  that the access rights the current FTP user has over the following  specific actions are granted. </blockquote>
<ul>
  <li><strong>add_anonymous(</strong><em>homedir</em><strong>[</strong>, **<em>kwargs</em><strong>])</strong><br />
    Add an anonymous user to the virtual users table.  AuthorizerError  exception raised on error conditions such as insufficient permissions,  missing home directory, or duplicate anonymous users. The keyword  arguments in kwargs are the same expected by add_user() method: perm, msg_login and msg_quit.  The optional <em>perm</em> keyword argument is a string defaulting to &quot;elr&quot; referencing &quot;read-only&quot; anonymous user's permission.  Using a &quot;write&quot; value results in a RuntimeWarning. </li>
</ul>
<ul>
  <li><strong>override_perm(</strong><em>directory</em>, <em>perm</em><strong>[</strong>, <em>recursive=False</em><strong>])</strong><br />
    Override permissions for a given directory. <em><strong>New in 0.5.0</strong></em> </li>
</ul>
<ul>
  <li><strong>validate_authentication(</strong><em>username</em>, <em>password</em><strong>)</strong><br />
    Return True if the supplied username and password match the stored credentials. </li>
</ul>
<ul>
  <li><strong>impersonate_user(</strong><em>username</em>, <em>password</em><strong>)</strong><br />
    Impersonate  another user (noop). It is always called before accessing the  filesystem. By default it does nothing. The subclass overriding this  method is expected to provide a mechanism to change the current user. <em><strong>New in 0.4.0</strong></em> </li>
</ul>
<ul>
  <li><strong>terminate_impersonation(</strong><em>username</em>, <em>password</em><strong>)</strong><br />
    Terminate  impersonation (noop). It is always called after having accessed the  filesystem. By default it does nothing. The subclass overriding this  method is expected to provide a mechanism to switch back to the  original user. <em><strong>New in 0.4.0</strong></em> </li>
</ul>
<ul>
  <li><strong>remove_user(</strong><em>username</em><strong>)</strong><br />
    Remove a user from the virtual user table. </li>
</ul>
<hr />
<p>class ftpserver.<strong>FTPHandler(</strong><em>conn, server</em><strong>)</strong> </p>
<blockquote>This class implements the FTP server Protocol Interpreter (see <a href="http://www.faqs.org/rfcs/rfc959.html" rel="nofollow">RFC-959</a>),  handling commands received from the client on the control channel by  calling the command's corresponding method (e.g. for received command  &quot;MKD pathname&quot;, ftp_MKD() method is called with pathname as the argument).  All relevant session information are stored in instance variables.  conn is the underlying socket object instance of the newly established connection, server is the FTPServer class instance.  Basic usage simply requires creating an instance of FTPHandler class and specify which authorizer instance it will going to use: </blockquote>
<pre>&gt;&gt;&gt; ftp_handler = ftpserver.FTPHandler<br />&gt;&gt;&gt; ftp_handler.authorizer = authorizer</pre>
<blockquote>All  relevant session information is stored in class attributes reproduced  below and can be modified before instantiating this class: </blockquote>
<ul>
  <li><strong>timeout</strong><br />
    The timeout which is  the maximum time a remote client may spend between FTP commands. If the  timeout triggers, the remote client will be kicked off (defaults to 300 seconds). <em><strong>New in 5.0</strong></em> </li>
</ul>
<ul>
  <li><strong>banner</strong><br />
    String sent when client connects (default &quot;pyftpdlib %s ready.&quot; %__ver__). </li>
</ul>
<ul>
  <li><strong>max_login_attempts</strong><br />
    Maximum number of wrong authentications before disconnecting (default 3). </li>
</ul>
<ul>
  <li><strong>permit_foreign_addresses</strong><br />
    Whether enable <a href="http://www.proftpd.org/docs/howto/FXP.html" rel="nofollow">FXP</a> feature (default False). </li>
</ul>
<ul>
  <li><strong>permit_privileged_ports</strong><br />
    Set to True if you want to permit active connections (PORT) over privileged ports (not recommended, default False). </li>
</ul>
<ul>
  <li><strong>masquerade_address</strong><br />
    The  &quot;masqueraded&quot; IP address to provide along PASV reply when pyftpdlib is  running behind a NAT or other types of gateways. When configured  pyftpdlib will hide its local address and instead use the public  address of your NAT (default None). </li>
</ul>
<ul>
  <li><strong>passive_ports</strong><br />
    What ports ftpd will use for its passive data transfers.  Value expected is a list of integers (e.g. range(60000, 65535)).  When configured pyftpdlib will no longer use kernel-assigned random ports (default None). </li>
</ul>
<ul>
  <li><strong>on_file_sent(</strong><em>file</em><strong>)</strong><br />
    Called every time a file has been successfully sent. <em><strong>New in 0.5.1</strong></em> </li>
</ul>
<ul>
  <li><strong>on_file_received(</strong><em>file</em><strong>)</strong><br />
    Called every time a file has been successfully received. <em><strong>New in 0.5.1</strong></em> </li>
</ul>
<hr />
<p>class ftpserver.<strong>DTPHandler(</strong><em>sock_obj, cmd_channel</em><strong>)</strong> </p>
<blockquote>This class handles the server-data-transfer-process (server-DTP, see <a href="http://www.faqs.org/rfcs/rfc959.html" rel="nofollow">RFC-959</a>) managing all transfer operations regarding the data channel.  sock_obj is the underlying socket object instance of the newly established connection, cmd_channel is the FTPHandler class instance.  Aside from timeout  class attribute and/or unless you want to add extra functionalities  like bandwidth throttling you shouldn't be interested in putting hands  on this class. </blockquote>
<ul>
  <li><strong>timeout</strong><br />
    The timeout which  roughly is the maximum time we permit data transfers to stall for with  no progress. If the timeout triggers, the remote client will be kicked  off. <em><strong>New in 5.0</strong></em> </li>
</ul>
<ul>
  <li><strong>ac_in_buffer_size</strong><br />
      <strong>ac_out_buffer_size</strong><br />
    The buffer sizes to use when receiving and sending data (both defaulting to 65536).  For LANs you may want this to be fairly large. Depending on available  memory and number of connected clients setting them to a lower value  can result in better performances. </li>
</ul>
<ul>
  <li><strong>get_transmitted_bytes()</strong><br />
    Return the number of transmitted bytes. </li>
</ul>
<hr />
<p>class ftpserver.<strong>ThrottledDTPHandler(</strong><em>sock_obj, cmd_channel</em><strong>)</strong> 
</p>
<blockquote>
  <p>A DTPHandler subclass which wraps sending and receiving in a data counter 
    and temporarily &quot;sleeps&quot; the channel so that you burst to no more 
    than x Kb/sec average. Use it instead of DTPHandler to set transfer rates 
    limits for both downloads and/or uploads (see the <a href="http://code.google.com/p/pyftpdlib/source/browse/trunk/demo/throttled_ftpd.py">demo 
    script</a> showing the example usage). </p>
  <p><em><strong>New in 0.5.2</strong></em></p>
</blockquote>
<ul>
  <li> read_limit<br />
    The maximum number of bytes to read (receive) in one second (defaults to 0 
    == no limit)</li>
</ul>
<ul>
  <li>write_limit<br />
    The maximum number of bytes to write (send) in one second (defaults to 0 == 
    no limit). </li>
</ul>
<hr />
<p>class ftpserver.<strong>FTPServer(</strong><em>address, handler</em><strong>)</strong> </p>
<blockquote>This class is an asyncore.dispatcher subclass.  It creates a FTP socket listening on address (a tuple containing the ip:port pair), dispatching the requests to a &quot;handler&quot; (typically FTPHandler class object).  It is typically used for starting asyncore polling loop: </blockquote>
<pre>&gt;&gt;&gt; address = ('127.0.0.1', 21)<br />&gt;&gt;&gt; ftpd = ftpserver.FTPServer(address, ftp_handler)<br />&gt;&gt;&gt; ftpd.serve_forever()</pre>
<ul>
  <li><strong>max_cons</strong><br />
    Number of maximum simultaneous connections accepted (default 0 == <em>no limit</em>). </li>
</ul>
<ul>
  <li><strong>max_cons_per_ip</strong><br />
    Number of maximum connections accepted for the same IP address (default 0 == <em>no limit</em>). </li>
</ul>
<ul>
  <li><strong>serve_forever([</strong><em>timeout=1</em><strong>[</strong>, <em>use_poll=False</em><strong>[</strong>, <em>map=None</em><strong>[</strong>, <em>count=None</em><strong>]]])</strong><br />
    A  wrap around asyncore.loop(); starts the asyncore polling loop including  running the scheduler. The arguments are the same expected by original <a href="http://docs.python.org/library/asyncore.html#asyncore.loop" rel="nofollow">asyncore.loop()</a> function. </li>
</ul>
<ul>
  <li><strong>close()</strong><br />
    Stop serving without disconnecting currently connected clients. </li>
</ul>
<ul>
  <li><strong>close_all([</strong><em>map=None</em><strong>[</strong>, <em>ignore_all=False</em><strong>]])</strong><br />
    Stop serving disconnecting also the currently connected clients. The map parameter is a dictionary whose items are the channels to close. If map is omitted, the default asyncore.socket_map is used. Having ignore_all parameter set to False results in raising exception in case of unexpected errors. </li>
</ul>
<hr />
<p>class ftpserver.<strong>AbstractedFS()</strong> </p>
<blockquote>A  class used to interact with the file system, providing a high level,  cross-platform interface compatible with both Windows and UNIX style  filesystems. It provides some utility methods to operate on pathnames  and the wraps around the common calls to interact with the filesystem  (e.g. open(), os.mkdir(), os.listdir(), etc...). These latter ones are  not reproduced below (see the source instead). </blockquote>
<ul>
  <li><strong>root</strong><br />
    User's home directory (&quot;real&quot;). </li>
</ul>
<ul>
  <li><strong>cwd</strong><br />
    User's current working directory (&quot;virtual&quot;). </li>
</ul>
<ul>
  <li><strong>ftpnorm(</strong><em>ftppath</em><strong>)</strong><br />
    Normalize  a &quot;virtual&quot; ftp pathname depending on the current working directory  (e.g. having &quot;/foo&quot; as current working directory &quot;x&quot; becomes &quot;/foo/x&quot;). <em><strong>New in 3.0</strong></em> </li>
</ul>
<ul>
  <li><strong>ftp2fs(</strong><em>ftppath</em><strong>)</strong><br />
    Translate  a &quot;virtual&quot; ftp pathname into equivalent absolute &quot;real&quot; filesystem  pathname (e.g. having &quot;/home/user&quot; as root directory &quot;x&quot; becomes  &quot;/home/user/x&quot;). <em><strong>New in 3.0</strong></em> </li>
</ul>
<ul>
  <li><strong>fs2ftp(</strong><em>fspath</em><strong>)</strong><br />
    Translate  a &quot;real&quot; filesystem pathname into equivalent absolute &quot;virtual&quot; ftp  pathname depending on the user's root directory (e.g. having  &quot;/home/user&quot; as root directory &quot;/home/user/x&quot; becomes &quot;/x&quot;. <em><strong>New in 3.0</strong></em> </li>
</ul>
<ul>
  <li><strong>validpath(</strong><em>path</em><strong>)</strong><br />
    Check  whether the path belongs to user's home directory. Expected argument is  a &quot;real&quot; filesystem path. If path is a symbolic link it is resolved to  check its real destination. Pathnames escaping from user's root  directory are considered not valid (return False). </li>
</ul>
<hr />
<p>class ftpserver.<strong>CallLater<a href="http://code.google.com/p/pyftpdlib/w/edit/CallLater"></a>(</strong><em>seconds</em>, <em>target</em> <strong>[</strong>, *<em>args</em> <strong>[</strong>, **<em>kwargs</em><strong>]])</strong> </p>
<blockquote>Calls  a function at a later time. It can be used to asynchronously schedule a  call within the polling loop without blocking it. The instance returned  is an object that can be used to cancel or reschedule the call. <em><strong>New in 0.5.0</strong></em> </blockquote>
<ul>
  <li><strong>cancelled</strong><br />
    Whether the call has been cancelled. </li>
</ul>
<ul>
  <li><strong>reset()</strong><br />
    Reschedule the call resetting the current countdown. </li>
</ul>
<ul>
  <li><strong>delay(</strong><em>seconds</em><strong>)</strong><br />
    Reschedule the call for a later time. </li>
</ul>
<ul>
  <li><strong>cancel()</strong><br />
    Unschedule the call. </li>
</ul>
<h1><a name="3.0_-_Customizing_your_FTP_server" id="3.0_-_Customizing_your_FTP_server">3.0 - Customizing your FTP server</a></h1>
<p><a name="3.0_-_Customizing_your_FTP_server" id="3.0_-_Customizing_your_FTP_server">Below  is a set of example scripts showing some of the possible customizations  that can be done with pyftpdlib. Some of them are included in </a><a href="http://code.google.com/p/pyftpdlib/source/browse/#svn/trunk/demo" rel="nofollow">demo</a> directory of pyftpdlib source distribution. </p>
<h2><a name="3.1_-_Building_a_Base_FTP_server" id="3.1_-_Building_a_Base_FTP_server">3.1 - Building a Base FTP server</a></h2>
<p><a name="3.1_-_Building_a_Base_FTP_server" id="3.1_-_Building_a_Base_FTP_server">The  script below is a basic configuration, and it's probably the best  starting point for understanding how things work. It uses the base DummyAuthorizer for adding a bunch of &quot;virtual&quot; users. </a></p>
<p><a name="3.1_-_Building_a_Base_FTP_server" id="3.1_-_Building_a_Base_FTP_server">It also sets a limit for connections by overriding FTPServer.max_cons and FTPServer.max_cons_per_ip  attributes which are intended to set limits for maximum connections to  handle simultaneously and maximum connections from the same IP address.  Overriding these variables is always a good idea (they default to 0, or &quot;no limit&quot;) since they are a good workaround for avoiding DoS attacks. </a></p>
<p><a href="http://pyftpdlib.googlecode.com/svn/trunk/demo/basic_ftpd.py" rel="nofollow">download script</a> </p>
<pre>#!/usr/bin/env python<br /># basic_ftpd.py<br />&nbsp; &nbsp;<br />&quot;&quot;&quot;A basic FTP server which uses a DummyAuthorizer for managing 'virtual<br />users', setting a limit for incoming connections.<br />&quot;&quot;&quot;<br />&nbsp; &nbsp;<br />import os<br />&nbsp; &nbsp;<br />from pyftpdlib import ftpserver<br />&nbsp; &nbsp;<br />&nbsp; &nbsp;<br />if __name__ == &quot;__main__&quot;:<br />&nbsp; &nbsp;<br />&nbsp; &nbsp; # Instantiate a dummy authorizer for managing 'virtual' users<br />&nbsp; &nbsp; authorizer = ftpserver.DummyAuthorizer()<br />&nbsp; &nbsp;<br />&nbsp; &nbsp; # Define a new user having full r/w permissions and a read-only<br />&nbsp; &nbsp; # anonymous user<br />&nbsp; &nbsp; authorizer.add_user('user', '12345', os.getcwd(), perm='elradfmw')<br />&nbsp; &nbsp; authorizer.add_anonymous(os.getcwd())<br />&nbsp; &nbsp;<br />&nbsp; &nbsp; # Instantiate FTP handler class<br />&nbsp; &nbsp; ftp_handler = ftpserver.FTPHandler<br />&nbsp; &nbsp; ftp_handler.authorizer = authorizer<br />&nbsp; &nbsp;<br />&nbsp; &nbsp; # Define a customized banner (string returned when client connects)<br />&nbsp; &nbsp; ftp_handler.banner = &quot;pyftpdlib %s based ftpd ready.&quot; %ftpserver.__ver__<br />&nbsp; &nbsp;<br />&nbsp; &nbsp; # Specify a masquerade address and the range of ports to use for<br />&nbsp; &nbsp; # passive connections. &nbsp;Decomment in case you're behind a NAT.<br />&nbsp; &nbsp; #ftp_handler.masquerade_address = '151.25.42.11'<br />&nbsp; &nbsp; #ftp_handler.passive_ports = range(60000, 65535)<br />&nbsp; &nbsp;<br />&nbsp; &nbsp; # Instantiate FTP server class and listen to 0.0.0.0:21<br />&nbsp; &nbsp; address = ('', 21)<br />&nbsp; &nbsp; ftpd = ftpserver.FTPServer(address, ftp_handler)<br />&nbsp; &nbsp;<br />&nbsp; &nbsp; # set a limit for connections<br />&nbsp; &nbsp; ftpd.max_cons = 256<br />&nbsp; &nbsp; ftpd.max_cons_per_ip = 5<br />&nbsp; &nbsp;<br />&nbsp; &nbsp; # start ftp server<br />&nbsp; &nbsp; ftpd.serve_forever()</pre>
<h2><a name="3.2_-_Logging_management" id="3.2_-_Logging_management">3.2 - Logging management</a></h2>
<p><a name="3.2_-_Logging_management" id="3.2_-_Logging_management">As mentioned, ftpserver.py comes with 3 different functions intended for a separate logging system: log(), logline() and logerror(). Let's suppose you don't want to print FTPd messages on screen but you want to write them into different files: <em>&quot;/var/log/ftpd.log&quot;</em> will be main log file, <em>&quot;/var/log/ftpd.lines.log&quot;</em> the one where you'll want to store commands and responses passing through the control connection. </a></p>
<p><a name="3.2_-_Logging_management" id="3.2_-_Logging_management">Here's one method this could be implemented: </a></p>
<pre><a name="3.2_-_Logging_management" id="3.2_-_Logging_management">#!/usr/bin/env python<br /># logging_management.py<br />&nbsp; &nbsp;<br />import os<br />import time<br />&nbsp; &nbsp;<br />from pyftpdlib import ftpserver<br />&nbsp; &nbsp;<br />now = lambda: time.strftime(&quot;[%Y-%b-%d %H:%M:%S]&quot;)<br />&nbsp; &nbsp;<br />def standard_logger(msg):<br />&nbsp; &nbsp; f1.write(&quot;%s %s\n&quot; %(now(), msg))<br />&nbsp; &nbsp;<br />def line_logger(msg):<br />&nbsp; &nbsp; f2.write(&quot;%s %s\n&quot; %(now(), msg))<br />&nbsp; &nbsp;<br />if __name__ == &quot;__main__&quot;:<br />&nbsp; &nbsp; f1 = open('ftpd.log', 'a')<br />&nbsp; &nbsp; f2 = open('ftpd.lines.log', 'a')<br />&nbsp; &nbsp; ftpserver.log = standard_logger<br />&nbsp; &nbsp; ftpserver.logline = line_logger<br /><br />&nbsp; &nbsp; authorizer = ftpserver.DummyAuthorizer()<br />&nbsp; &nbsp; authorizer.add_anonymous(os.getcwd())<br />&nbsp; &nbsp; ftp_handler = ftpserver.FTPHandler<br />&nbsp; &nbsp; ftp_handler.authorizer = authorizer<br />&nbsp; &nbsp; address = ('', 21)<br />&nbsp; &nbsp; ftpd = ftpserver.FTPServer(address, ftp_handler)<br />&nbsp; &nbsp; ftpd.serve_forever()</a></pre>
<h2><a name="3.3_-_Storing_passwords_as_hash_digests" id="3.3_-_Storing_passwords_as_hash_digests">3.3 - Storing passwords as hash digests</a></h2>
<p><a name="3.3_-_Storing_passwords_as_hash_digests" id="3.3_-_Storing_passwords_as_hash_digests">Using FTP server library with the default DummyAuthorizer  means that password will be stored in clear-text. An end-user ftpd  using the default dummy authorizer would typically require a  configuration file for authenticating users and their passwords but  storing clear-text passwords is of course undesirable. </a></p>
<p><a name="3.3_-_Storing_passwords_as_hash_digests" id="3.3_-_Storing_passwords_as_hash_digests">The  most common way to do things in such case would be first creating new  users and then storing their usernames + passwords as hash digests into  a file or wherever you find it convenient. </a></p>
<p><a name="3.3_-_Storing_passwords_as_hash_digests" id="3.3_-_Storing_passwords_as_hash_digests">The  example below shows how to easily create an encrypted account storage  system by storing passwords as one-way hashes by using md5 algorithm.  This could be easily done by using the <strong>hashlib</strong> module included with Python stdlib and by sub-classing the original DummyAuthorizer class overriding its validate_authentication() method. </a></p>
<p><a href="http://pyftpdlib.googlecode.com/svn/trunk/demo/md5_ftpd.py" rel="nofollow">download script</a> </p>
<pre>#!/usr/bin/env python<br /># md5_ftpd.py<br />&nbsp; &nbsp;<br />&quot;&quot;&quot;A basic ftpd storing passwords as hash digests (platform independent).<br />&quot;&quot;&quot;<br />&nbsp; &nbsp;<br />import os<br />try:<br />&nbsp; &nbsp; from hashlib import md5<br />except ImportError:<br />&nbsp; &nbsp; # backward compatibility with Python &lt; 2.5<br />&nbsp; &nbsp; from md5 import new as md5<br />&nbsp; &nbsp;<br />from pyftpdlib import ftpserver<br />&nbsp; &nbsp;<br />&nbsp; &nbsp;<br />class DummyMD5Authorizer(ftpserver.DummyAuthorizer):<br />&nbsp; &nbsp;<br />&nbsp; &nbsp; def validate_authentication(self, username, password):<br />&nbsp; &nbsp; &nbsp; &nbsp; hash = md5(password).hexdigest()<br />&nbsp; &nbsp; &nbsp; &nbsp; return self.user_table[username]['pwd'] == hash<br />&nbsp; &nbsp;<br />if __name__ == &quot;__main__&quot;:<br />&nbsp; &nbsp; # get a hash digest from a clear-text password<br />&nbsp; &nbsp; hash = md5('12345').hexdigest()<br />&nbsp; &nbsp; authorizer = DummyMD5Authorizer()<br />&nbsp; &nbsp; authorizer.add_user('user', hash, os.getcwd(), perm='elradfmw')<br />&nbsp; &nbsp; authorizer.add_anonymous(os.getcwd())<br />&nbsp; &nbsp; ftp_handler = ftpserver.FTPHandler<br />&nbsp; &nbsp; ftp_handler.authorizer = authorizer<br />&nbsp; &nbsp; address = ('', 21)<br />&nbsp; &nbsp; ftpd = ftpserver.FTPServer(address, ftp_handler)<br />&nbsp; &nbsp; ftpd.serve_forever()</pre>
<h2><a name="3.4_-_Unix_FTP_Server" id="3.4_-_Unix_FTP_Server">3.4 - Unix FTP Server</a></h2>
<p><a name="3.4_-_Unix_FTP_Server" id="3.4_-_Unix_FTP_Server">If you're running a Unix system you may want to configure your ftpd to include support for &quot;real&quot; users existing on the system. </a></p>
<p><a name="3.4_-_Unix_FTP_Server" id="3.4_-_Unix_FTP_Server">The example below shows how to use </a><a href="http://docs.python.org/lib/module-pwd.html" rel="nofollow">pwd</a> and <a href="http://docs.python.org/lib/module-spwd.html" rel="nofollow">spwd</a> modules available in <em>Python 2.5</em> or greater (UNIX systems only) to interact with UNIX user account and  shadow passwords database and also to automatically get the user's home  directory. </p>
<p>impersonate_user() and terminate_impersonation()  methods of the dummy authorizer are overridden to provide the proper  mechanism to reflect the current logged-in user every time he's going  to access the filesystem. </p>
<p>Note that the users you're going to add through the add_user method must already exist on the system. </p>
<p><a href="http://pyftpdlib.googlecode.com/svn/trunk/demo/unix_ftpd.py" rel="nofollow">download script</a> </p>
<pre>#!/usr/bin/env python<br /># unix_ftpd.py<br />&nbsp; &nbsp;<br />&quot;&quot;&quot;A ftpd using local unix account database to authenticate users<br />(users must already exist).<br />&nbsp; &nbsp;<br />It also provides a mechanism to (temporarily) impersonate the system<br />users every time they are going to perform filesystem operations.<br />&quot;&quot;&quot;<br />&nbsp; &nbsp;<br />import os<br />import pwd, spwd, crypt<br />&nbsp; &nbsp;<br />from pyftpdlib import ftpserver<br />&nbsp; &nbsp;<br />&nbsp; &nbsp;<br />class UnixAuthorizer(ftpserver.DummyAuthorizer):<br />&nbsp; &nbsp;<br />&nbsp; &nbsp; # the uid/gid the daemon runs under<br />&nbsp; &nbsp; PROCESS_UID = os.getuid()<br />&nbsp; &nbsp; PROCESS_GID = os.getgid()<br />&nbsp; &nbsp;<br />&nbsp; &nbsp; def add_user(self, username, homedir=None, **kwargs):<br />&nbsp; &nbsp; &nbsp; &nbsp; &quot;&quot;&quot;Add a &quot;real&quot; system user to the virtual users table.<br />&nbsp; &nbsp;<br />&nbsp; &nbsp; &nbsp; &nbsp; If no home argument is specified the user's home directory will<br />&nbsp; &nbsp; &nbsp; &nbsp; be used.<br />&nbsp; &nbsp;<br />&nbsp; &nbsp; &nbsp; &nbsp; The keyword arguments in kwargs are the same expected by the<br />&nbsp; &nbsp; &nbsp; &nbsp; original add_user method: &quot;perm&quot;, &quot;msg_login&quot; and &quot;msg_quit&quot;.<br />&nbsp; &nbsp; &nbsp; &nbsp; &quot;&quot;&quot;<br />&nbsp; &nbsp; &nbsp; &nbsp; # get the list of all available users on the system and check<br />&nbsp; &nbsp; &nbsp; &nbsp; # if provided username exists<br />&nbsp; &nbsp; &nbsp; &nbsp; users = [entry.pw_name for entry in pwd.getpwall()]<br />&nbsp; &nbsp; &nbsp; &nbsp; if not username in users:<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; raise ftpserver.AuthorizerError('No such user &quot;%s&quot;.' %username)<br />&nbsp; &nbsp; &nbsp; &nbsp; if not homedir:<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; homedir = pwd.getpwnam(username).pw_dir<br />&nbsp; &nbsp; &nbsp; &nbsp; ftpserver.DummyAuthorizer.add_user(self, username, '', homedir,**kwargs)<br />&nbsp; &nbsp;<br />&nbsp; &nbsp; def add_anonymous(self, homedir=None, realuser=&quot;nobody&quot;, **kwargs):<br />&nbsp; &nbsp; &nbsp; &nbsp; &quot;&quot;&quot;Add an anonymous user to the virtual users table.<br /><br />&nbsp; &nbsp; &nbsp; &nbsp; If no homedir argument is specified the realuser's home<br />&nbsp; &nbsp; &nbsp; &nbsp; directory will possibly be determined and used.<br /><br />&nbsp; &nbsp; &nbsp; &nbsp; realuser argument specifies the system user to use for managing<br />&nbsp; &nbsp; &nbsp; &nbsp; anonymous sessions. &nbsp;On many UNIX systems &quot;nobody&quot; is tipically<br />&nbsp; &nbsp; &nbsp; &nbsp; used but it may change (e.g. &quot;ftp&quot;).<br />&nbsp; &nbsp; &nbsp; &nbsp; &quot;&quot;&quot;<br />&nbsp; &nbsp; &nbsp; &nbsp; users = [entry.pw_name for entry in pwd.getpwall()]<br />&nbsp; &nbsp; &nbsp; &nbsp; if not realuser in users:<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; raise ftpserver.AuthorizerError('No such user &quot;%s&quot;.' %realuser)<br />&nbsp; &nbsp; &nbsp; &nbsp; if not homedir:<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; homedir = pwd.getpwnam(realuser).pw_dir<br />&nbsp; &nbsp; &nbsp; &nbsp; ftpserver.DummyAuthorizer.add_anonymous(self, homedir, **kwargs)<br />&nbsp; &nbsp; &nbsp; &nbsp; self.anon_user = realuser<br />&nbsp; &nbsp;<br />&nbsp; &nbsp; def validate_authentication(self, username, password):<br />&nbsp; &nbsp; &nbsp; &nbsp; if (username == &quot;anonymous&quot;) and self.has_user('anonymous'):<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; username = self.anon_user<br />&nbsp; &nbsp;<br />&nbsp; &nbsp; &nbsp; &nbsp; pw1 = spwd.getspnam(username).sp_pwd<br />&nbsp; &nbsp; &nbsp; &nbsp; pw2 = crypt.crypt(password, pw1)<br />&nbsp; &nbsp; &nbsp; &nbsp; return pw1 == pw2<br />&nbsp; &nbsp;<br />&nbsp; &nbsp; def impersonate_user(self, username, password):<br />&nbsp; &nbsp; &nbsp; &nbsp; if (username == &quot;anonymous&quot;) and self.has_user('anonymous'):<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; username = self.anon_user<br />&nbsp; &nbsp; &nbsp; &nbsp; uid = pwd.getpwnam(username).pw_uid<br />&nbsp; &nbsp; &nbsp; &nbsp; gid = pwd.getpwnam(username).pw_gid<br />&nbsp; &nbsp; &nbsp; &nbsp; os.setegid(gid)<br />&nbsp; &nbsp; &nbsp; &nbsp; os.seteuid(uid)<br />&nbsp; &nbsp;<br />&nbsp; &nbsp; def terminate_impersonation(self):<br />&nbsp; &nbsp; &nbsp; &nbsp; os.setegid(self.PROCESS_GID)<br />&nbsp; &nbsp; &nbsp; &nbsp; os.seteuid(self.PROCESS_UID)<br />&nbsp; &nbsp;<br />&nbsp; &nbsp;<br />if __name__ == &quot;__main__&quot;:<br />&nbsp; &nbsp; authorizer = UnixAuthorizer()<br />&nbsp; &nbsp; # add a user (note: user must already exists)<br />&nbsp; &nbsp; authorizer.add_user('user', perm='elradfmw')<br />&nbsp; &nbsp; authorizer.add_anonymous(os.getcwd())<br />&nbsp; &nbsp; ftp_handler = ftpserver.FTPHandler<br />&nbsp; &nbsp; ftp_handler.authorizer = authorizer<br />&nbsp; &nbsp; address = ('', 21)<br />&nbsp; &nbsp; ftpd = ftpserver.FTPServer(address, ftp_handler)<br />&nbsp; &nbsp; ftpd.serve_forever()</pre>
<h2><a name="3.5_-_Windows_NT_FTP_Server" id="3.5_-_Windows_NT_FTP_Server">3.5 - Windows NT FTP Server</a></h2>
<p><a name="3.5_-_Windows_NT_FTP_Server" id="3.5_-_Windows_NT_FTP_Server">The  following code shows how to implement a basic authorizer for a Windows  NT workstation to authenticate against existing Windows user accounts.  This code uses Mark Hammond's </a><a href="http://starship.python.net/crew/mhammond/win32/" rel="nofollow">pywin32</a> extension which is required to be installed previously. </p>
<p>Note that, as for UNIX authorizer, the users you're going to add through the add_user method must already exist on the system. </p>
<p><a href="http://pyftpdlib.googlecode.com/svn/trunk/demo/winnt_ftpd.py" rel="nofollow">download script</a> </p>
<pre>#!/usr/bin/env python<br /># winnt_ftpd.py<br />&nbsp; &nbsp;<br />&quot;&quot;&quot;A ftpd using local Windows NT account database to authenticate users<br />(users must already exist).<br />&nbsp; &nbsp;<br />It also provides a mechanism to (temporarily) impersonate the system<br />users every time they are going to perform filesystem operations.<br />&quot;&quot;&quot;<br />&nbsp; &nbsp;<br />import os<br />import win32security, win32net, pywintypes, win32con<br />&nbsp; &nbsp;<br />from pyftpdlib import ftpserver<br />&nbsp; &nbsp;<br />&nbsp; &nbsp;<br />def get_profile_dir(username):<br />&nbsp; &nbsp; &quot;&quot;&quot;Return the user's profile directory.&quot;&quot;&quot;<br />&nbsp; &nbsp; import _winreg, win32api<br />&nbsp; &nbsp; sid = win32security.ConvertSidToStringSid(<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; win32security.LookupAccountName(None, username)[0])<br />&nbsp; &nbsp; try:<br />&nbsp; &nbsp; &nbsp; &nbsp; key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; r&quot;SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList&quot;+&quot;\\&quot;+sid)<br />&nbsp; &nbsp; except WindowsError:<br />&nbsp; &nbsp; &nbsp; &nbsp; raise ftpserver.AuthorizerError(&quot;No profile directory defined for %s &quot;<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &quot;user&quot; %username)<br />&nbsp; &nbsp; value = _winreg.QueryValueEx(key, &quot;ProfileImagePath&quot;)[0]<br />&nbsp; &nbsp; return win32api.ExpandEnvironmentStrings(value)<br />&nbsp; &nbsp;<br />&nbsp; &nbsp;<br />class WinNtAuthorizer(ftpserver.DummyAuthorizer):<br />&nbsp; &nbsp;<br />&nbsp; &nbsp; def add_user(self, username, homedir=None, **kwargs):<br />&nbsp; &nbsp; &nbsp; &nbsp; &quot;&quot;&quot;Add a &quot;real&quot; system user to the virtual users table.<br />&nbsp; &nbsp;<br />&nbsp; &nbsp; &nbsp; &nbsp; If no homedir argument is specified the user's profile<br />&nbsp; &nbsp; &nbsp; &nbsp; directory will possibly be determined and used.<br />&nbsp; &nbsp;<br />&nbsp; &nbsp; &nbsp; &nbsp; The keyword arguments in kwargs are the same expected by the<br />&nbsp; &nbsp; &nbsp; &nbsp; original add_user method: &quot;perm&quot;, &quot;msg_login&quot; and &quot;msg_quit&quot;.<br />&nbsp; &nbsp; &nbsp; &nbsp; &quot;&quot;&quot;<br />&nbsp; &nbsp; &nbsp; &nbsp; # get the list of all available users on the system and check<br />&nbsp; &nbsp; &nbsp; &nbsp; # if provided username exists<br />&nbsp; &nbsp; &nbsp; &nbsp; users = [entry['name'] for entry in win32net.NetUserEnum(None, 0)[0]]<br />&nbsp; &nbsp; &nbsp; &nbsp; if not username in users:<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; raise ftpserver.AuthorizerError('No such user &quot;%s&quot;.' %username)<br />&nbsp; &nbsp; &nbsp; &nbsp; if not homedir:<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; homedir = get_profile_dir(username)<br />&nbsp; &nbsp; &nbsp; &nbsp; ftpserver.DummyAuthorizer.add_user(self, username, '', homedir,<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;**kwargs)<br />&nbsp; &nbsp;<br />&nbsp; &nbsp; def add_anonymous(self, homedir=None, realuser=&quot;Guest&quot;,<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; password=&quot;&quot;, **kwargs):<br />&nbsp; &nbsp; &nbsp; &nbsp; &quot;&quot;&quot;Add an anonymous user to the virtual users table.<br />&nbsp; &nbsp;<br />&nbsp; &nbsp; &nbsp; &nbsp; If no homedir argument is specified the realuser's profile<br />&nbsp; &nbsp; &nbsp; &nbsp; directory will possibly be determined and used.<br />&nbsp; &nbsp;<br />&nbsp; &nbsp; &nbsp; &nbsp; realuser and password arguments are the credentials to use for<br />&nbsp; &nbsp; &nbsp; &nbsp; managing anonymous sessions.<br />&nbsp; &nbsp; &nbsp; &nbsp; The same behaviour is followed in IIS where the Guest account<br />&nbsp; &nbsp; &nbsp; &nbsp; is used to do so (note: it must be enabled first).<br />&nbsp; &nbsp; &nbsp; &nbsp; &quot;&quot;&quot;<br />&nbsp; &nbsp; &nbsp; &nbsp; users = [entry['name'] for entry in win32net.NetUserEnum(None, 0)[0]]<br />&nbsp; &nbsp; &nbsp; &nbsp; if not realuser in users:<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; raise ftpserver.AuthorizerError('No such user &quot;%s&quot;.' %realuser)<br />&nbsp; &nbsp; &nbsp; &nbsp; if not homedir:<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; homedir = get_profile_dir(realuser)<br />&nbsp; &nbsp; &nbsp; &nbsp; # make sure provided credentials are valid, otherwise an exception<br />&nbsp; &nbsp; &nbsp; &nbsp; # will be thrown; to do so we actually try to impersonate the user<br />&nbsp; &nbsp; &nbsp; &nbsp; self.impersonate_user(realuser, password)<br />&nbsp; &nbsp; &nbsp; &nbsp; self.terminate_impersonation()<br />&nbsp; &nbsp; &nbsp; &nbsp; ftpserver.DummyAuthorizer.add_anonymous(self, homedir, **kwargs)<br />&nbsp; &nbsp; &nbsp; &nbsp; self.anon_user = realuser<br />&nbsp; &nbsp; &nbsp; &nbsp; self.anon_pwd = password<br />&nbsp; &nbsp;<br />&nbsp; &nbsp; def validate_authentication(self, username, password):<br />&nbsp; &nbsp; &nbsp; &nbsp; if (username == &quot;anonymous&quot;) and self.has_user('anonymous'):<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; username = self.anon_user<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; password = self.anon_pwd<br />&nbsp; &nbsp; &nbsp; &nbsp; try:<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; win32security.LogonUser(username, None, password,<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; win32con.LOGON32_LOGON_INTERACTIVE,<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; win32con.LOGON32_PROVIDER_DEFAULT)<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return True<br />&nbsp; &nbsp; &nbsp; &nbsp; except pywintypes.error:<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return False<br />&nbsp; &nbsp;<br />&nbsp; &nbsp; def impersonate_user(self, username, password):<br />&nbsp; &nbsp; &nbsp; &nbsp; if (username == &quot;anonymous&quot;) and self.has_user('anonymous'):<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; username = self.anon_user<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; password = self.anon_pwd<br />&nbsp; &nbsp; &nbsp; &nbsp; handler = win32security.LogonUser(username, None, password,<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; win32con.LOGON32_LOGON_INTERACTIVE,<br />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; win32con.LOGON32_PROVIDER_DEFAULT)<br />&nbsp; &nbsp; &nbsp; &nbsp; win32security.ImpersonateLoggedOnUser(handler)<br />&nbsp; &nbsp; &nbsp; &nbsp; handler.Close()<br />&nbsp; &nbsp;<br />&nbsp; &nbsp; def terminate_impersonation(self):<br />&nbsp; &nbsp; &nbsp; &nbsp; win32security.RevertToSelf()<br /><br /><br />if __name__ == &quot;__main__&quot;:<br />&nbsp; &nbsp; authorizer = WinNtAuthorizer()<br />&nbsp; &nbsp; # add a user (note: user must already exists)<br />&nbsp; &nbsp; authorizer.add_user('user', perm='elradfmw')<br />&nbsp; &nbsp; # add an anonymous user using Guest account to handle the anonymous<br />&nbsp; &nbsp; # sessions (note: Guest must be enabled first)<br />&nbsp; &nbsp; authorizer.add_anonymous(os.getcwd())<br />&nbsp; &nbsp; ftp_handler = ftpserver.FTPHandler<br />&nbsp; &nbsp; ftp_handler.authorizer = authorizer<br />&nbsp; &nbsp; address = ('', 21)<br />&nbsp; &nbsp; ftpd = ftpserver.FTPServer(address, ftp_handler)<br />&nbsp; &nbsp; ftpd.serve_forever()</pre>
<h1><a name="4.0_-_Advanced_usages" id="4.0_-_Advanced_usages">4.0 - Advanced usages</a></h1>
<h2><a name="4.1_-_FTPS_(FTP_over_TLS/SSL)_server" id="4.1_-_FTPS_(FTP_over_TLS/SSL)_server">4.1 - FTPS (FTP over TLS/SSL) server</a></h2>
<p><a name="4.1_-_FTPS_(FTP_over_TLS/SSL)_server" id="4.1_-_FTPS_(FTP_over_TLS/SSL)_server">Although the standard code base does not offer any &quot;official&quot; FTPS support yet starting from version </a><a href="http://pyftpdlib.googlecode.com/files/pyftpdlib-0.5.1.tar.gz" rel="nofollow">0.5.1</a> the <a href="http://code.google.com/p/pyftpdlib/source/browse/trunk/demo" rel="nofollow">demo</a> directory contains a <a href="http://code.google.com/p/pyftpdlib/source/browse/trunk/demo/tls_ftpd.py" rel="nofollow">script</a> which implements a simple FTPS daemon supporting both TLS and SSL protocols and <strong>AUTH</strong>, <strong>PBSZ</strong> and <strong>PROT</strong> commands as defined in <a href="http://www.ietf.org/rfc/rfc4217.txt" rel="nofollow">RFC-4217</a>. </p>
<p>This is possible thanks to the new <a href="http://docs.python.org/library/ssl.html#module-ssl" rel="nofollow">ssl module</a> introduced in Python 2.6. </p>
<p><a href="http://pyftpdlib.googlecode.com/svn/trunk/demo/tls_ftpd.py" rel="nofollow">download script</a></p>
<h2><a name="4.2_-_Adding_bandwidth_throttling_capabilities" id="4.2_-_Adding_bandwidth_throttling_capabilities">4.2 - Adding bandwidth throttling capabilities</a></h2>
<p><a name="4.2_-_Adding_bandwidth_throttling_capabilities" id="4.2_-_Adding_bandwidth_throttling_capabilities">An important feature for an ftpd is limiting the speed for downloads and uploads affecting the data channel. </a></p>
<p><a name="4.2_-_Adding_bandwidth_throttling_capabilities" id="4.2_-_Adding_bandwidth_throttling_capabilities">The  basic idea behind this script is to wrap sending and receiving in a  data counter and temporary &quot;sleep&quot; the data channel so that you burst  to no more than x Kb/sec average. Such sleep must be &quot;asynchronous&quot;  since we want to avoid the polling loop from blocking. </a></p>
<p><a name="4.2_-_Adding_bandwidth_throttling_capabilities" id="4.2_-_Adding_bandwidth_throttling_capabilities">To accomplish such behaviour I used the CallLater class to implement the asynchronous sleeps and ovverridden the original DTPHandler  class. When the new DTPHandler realizes that more than x Kb in a second  are being transmitted it temporary blocks the transfer for a certain  number of seconds. </a></p>
<p><a href="http://pyftpdlib.googlecode.com/svn/trunk/demo/throttled_ftpd.py" rel="nofollow">download script</a> </p>
<pre>&nbsp;</pre>
